package com.kaver.sso.helper;

import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtil {

	private static final long DEFAULT_TIMEOUT = 60L;
	@SuppressWarnings("deprecation")
	private static OkHttpClient client = new OkHttpClient.Builder().connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
			.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS).writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS).sslSocketFactory(createSSLSocketFactory())
            .hostnameVerifier(new TrustAllHostnameVerifier()).build();
	
	public static String doPost(String json, Map<String, String> headers, String url) throws IOException {
        Response response = null;
        try {
            Request request =
                new Request.Builder().url(url).headers(buildHeaders(headers)).post(buildRequestBody(json)).build();
            response = client.newCall(request).execute();
            if (response.code() != 200) {
                throw new IOException("http status is not 200, it is " + response.code());
            }
            String result = new String(response.body().bytes());
            return result;
        } finally {
            if (response != null) {
                response.close();
            }
        }

    }
	public static String doPost(Map<String, String> params, Map<String, String> headers, String url)
			throws IOException {
		Response response = null;
		try {
			Request request = new Request.Builder().url(url).headers(buildHeaders(headers)).post(buildRequestBody(params))
					.build();
			response = client.newCall(request).execute();
			if (response.code() != 200) {
				throw new IOException("http status is not 200 ,it is " + response.code());
			}
			String result = new String(response.body().bytes());
			return result;
		} finally {
			if (response != null) {
				response.close();
			}
		}
		
	}
	public static String doGet(Map<String, String> headers, String url)
        throws IOException {
    Response response = null;
    try {
        Request request = new Request.Builder().url(url).headers(buildHeaders(headers)).get()
                .build();
        response = client.newCall(request).execute();
        if (response.code() != 200) {
            throw new IOException("http status is not 200 ,it is " + response.code());
        }
        String result = new String(response.body().bytes());
        return result;
    } finally {
        if (response != null) {
            response.close();
        }
    }
    
}
	private static RequestBody buildRequestBody(String json) {
        return RequestBody.create(MediaType.parse("application/json"), json);
    }
	private static Headers buildHeaders(Map<String, String> headers) {
		Headers.Builder builder = new Headers.Builder();
		if (headers != null) {
            headers.forEach((k, v) -> {
                builder.add(k, v);
            });
        }
		return builder.build();
	}

	private static RequestBody buildRequestBody(Map<String, String> params) {
		FormBody.Builder builder = new FormBody.Builder();
		params.forEach((k, v) -> {
			builder.add(k, v);
		});
		return builder.build();
	}
	
	private static class TrustAllCerts implements X509TrustManager{

		@Override
		public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
			
		}
		@Override
		public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
			
		}
		@Override
		public X509Certificate[] getAcceptedIssuers() {
			return new X509Certificate[0];
		}
	}
	
	private static class  TrustAllHostnameVerifier implements HostnameVerifier{

		@Override
		public boolean verify(String arg0, SSLSession arg1) {
			return true;
		}
	}
	
	private static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null,  new TrustManager[] { new TrustAllCerts() }, new SecureRandom());
 
            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }
 
        return ssfFactory;
    }

}
